const fs = require('fs');
const http = require('http');
const url = require('url');
const path = require('path');

function handle_incoming_request(req, res) {
    if(req.method.toLowerCase() == 'get' && req.url.substr(0, 8) == '/content') {
        console.log("file path:"+ req.url.substring(9));
        server_static_file(req.url.substring(9), res)
    } else {
        res.writeHead(404, {"Content-Type": "application/json"});
        var out = {error: "not found", message: req.url + " not found"};
        res.end(JSON.stringify(out))
    }
}

function server_static_file(file, res) {
    fs.exists(file, function(exists) {
        if(!exists) {
            res.writeHead(404, {"Content-Type": "application/json"});
            var out = {err: "not found", message: file + " not found"};
            res.end(JSON.stringify(out));
            return;
        }
        var rs = fs.createReadStream(file);
        rs.on('error', function() {
            res.end();
        });
        var ct = content_type_for_path(file);
        res.writeHead(200, {"Content-Type": ct});
        rs.pipe(res);
    })
}
function content_type_for_path(file) {
    var ext = path.extname(file);
    switch (ext.toLowerCase()) {
        case '.html': return "text/html";
        case '.js': return "text/javascript";
        case '.css': return "text/css";
        case '.jpg': return "image/jpeg";
        default: return "text/plain";
    }
}
var s = http.createServer(handle_incoming_request);
s.listen(8080);